package sinProblemNoExecutor;

public class SinProb {

	private Thread[] threads;

	private int N;
	private volatile int value;

	public SinProb(int N, int nThreads) {

		this.N = N;
		value = -N;
		threads = new Thread[nThreads];

	}

	public void compute() {
		final int nThreads = threads.length;

		for (int i = 0; i < nThreads; i++) {

			threads[i] = new Thread(new MyTask(createBuffer(i)));

			threads[i].start();

		}

		for (int k = 0; k < nThreads; k++) {
			try {
				threads[k].join();
			} catch (InterruptedException e) {

				e.printStackTrace();
			}

		}

	}

	private int[] createBuffer(int i) {
		int avgSizeOfBuffer = (2 * N + 1) / threads.length;

		int[] argBuffer;
		if (avgSizeOfBuffer <= 1) {
			throw new IllegalArgumentException(
					"There is too many threads for this range of numbers!");
		}
		if (i < threads.length - 1) {
			argBuffer = new int[avgSizeOfBuffer];
		} else {
			argBuffer = new int[avgSizeOfBuffer + (2 * N + 1)
					- ((i + 1) * avgSizeOfBuffer)];

		}
		for (int j = 0; j < argBuffer.length; j++) {
			argBuffer[j] = value++;
		}

		return argBuffer;

	}

}
